package com.sun.chunqiugeneratorbasic.generator;


import com.sun.chunqiugeneratorbasic.model.MainTemplateConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/*
 * 动态文件生成器
 * */
public class DynamicGenerator {

    //TODO
    //更泛用的生成方法
    /*
     * 生成方法
     * @param inputPath 模板文件路径
     * @param outputPath 输出文件路径
     * @param model 模板数据模型
     * */
    public static void main(String[] args) {
    String projectPath = System.getProperty("user.dir")+File.separator+"chunqiu-generator-basic";
    String inputPath=projectPath+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"templates"+File.separator+"MainTemplate.java.ftl";
    String outputPath=projectPath+File.separator+"MainTemplate.java";
    MainTemplateConfig mainTemplateConfig = new MainTemplateConfig();
    mainTemplateConfig.setAuthor("chunqiu");
    mainTemplateConfig.setOutputText("求和结果：");
    mainTemplateConfig.setLoop(false);
    doGenerator(inputPath,outputPath,mainTemplateConfig);


    }
    //TODO
    //更泛用的生成方法
    /*
    * 生成方法
    * @param inputPath 模板文件路径
    * @param outputPath 输出文件路径
    * @param model 模板数据模型
    * */

    public static void doGenerator(String inputPath, String outputPath, Object model) {
        Configuration configuration = new Configuration();

        File templateDir = new File(inputPath).getParentFile();
        String templateName = new File(inputPath).getName();

        configuration.setDefaultEncoding("UTF-8");
        configuration.setNumberFormat("0.#####");

        try {
            configuration.setDirectoryForTemplateLoading(templateDir);
            Template template = configuration.getTemplate(templateName);
            Writer out = new FileWriter(outputPath);
            template.process(model, out);
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
    }
}
